package com.demo.action;

import com.demo.serviceI.DemoService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
public class DemoAction {

    @Autowired
    private DemoService demoService;

    /**
     * 健康检查json串模拟
     * @return
     */
    @RequestMapping(value = "health.json")
    public String healt(){

        return "{\"status\":\"UP\",\"diskSpace\":{\"status\":\"UP\",\"total\":249769230336,\"free\":71914618880,\"threshold\":10485760},\"db\":{\"status\":\"UP\",\"database\":\"MySQL\",\"hello\":1}}";
    }

    /**
     * 条件注解使用
     * @return
     */
    @RequestMapping(value = "user/info")
    public String info(){

        return demoService.info();
    }

    /**
     * 异步调用方法
     */
    @RequestMapping(value = "print")
    public void print(){
        for (int i = 0; i < 100; i++) {
            demoService.print(i);
        }
    }

    /**
     * 服务端推送技术
     */
    @RequestMapping(value = "serverPush",produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public String serverPush(){

        Map<String,String> demo = new HashMap<>(1);
        demo.put("name","张三"+new Random().nextInt());
        ObjectMapper objectMapper = new ObjectMapper();
        String s = "data:";
        try {
            s+= objectMapper.writeValueAsString(demo)+"\n\n";
            System.out.println(s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 服务端推送技术
     * @return
     */
    @RequestMapping(value = "push")
    public DeferredResult<Map<String,String>> push(){
        DeferredResult<Map<String,String>> deferredResult = new DeferredResult<>();

        deferredResult.onCompletion(()->{});

        deferredResult.onError((x)->{});

        deferredResult.onTimeout(()->{
            deferredResult.setResult(new HashMap<>());
        });

        return deferredResult;
    }
}
